//
//  ZSNBroadcastVC.swift
//  AgoraBroadcastZhaosn
//
//  Created by zhaosuning on 2022/1/17.
//

import UIKit
import AgoraRtcKit

//补齐信息

let appid = ""

let channelname = ""

let token = ""

class ZSNBroadcastVC: UIViewController {
    
    var agoraKit : AgoraRtcEngineKit!
    var localView: UIView!
    var remoteView: UIView!
    

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        self.title = "直播"
        
        let btnJoinChannel = UIButton.init(frame: CGRect(x: 30, y: 100, width: 160, height: 50))
        btnJoinChannel.backgroundColor = UIColor.green
        btnJoinChannel.setTitle("点击进入频道", for: .normal)
        btnJoinChannel.layer.cornerRadius = 23.5
        btnJoinChannel.titleLabel?.textAlignment = .center
        btnJoinChannel.layer.masksToBounds = true
        btnJoinChannel.titleLabel?.font = UIFont.systemFont(ofSize: 20)
        btnJoinChannel.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
        btnJoinChannel.addTarget(self, action: #selector(btnJoinChannelClick), for: UIControl.Event.touchUpInside)
        self.view.addSubview(btnJoinChannel)
        
        let btnLeaveChannel = UIButton.init(frame: CGRect(x: 30, y: 160, width: 160, height: 50))
        btnLeaveChannel.backgroundColor = UIColor.green
        btnLeaveChannel.setTitle("离开频道", for: .normal)
        btnLeaveChannel.layer.cornerRadius = 23.5
        btnLeaveChannel.titleLabel?.textAlignment = .center
        btnLeaveChannel.layer.masksToBounds = true
        btnLeaveChannel.titleLabel?.font = UIFont.systemFont(ofSize: 20)
        btnLeaveChannel.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
        btnLeaveChannel.addTarget(self, action: #selector(btnLeaveChannelClick), for: UIControl.Event.touchUpInside)
        self.view.addSubview(btnLeaveChannel)
        
        let btnDestroy = UIButton.init(frame: CGRect(x: 30, y: 220, width: 160, height: 50))
        btnDestroy.backgroundColor = UIColor.green
        btnDestroy.setTitle("销毁", for: .normal)
        btnDestroy.layer.cornerRadius = 23.5
        btnDestroy.titleLabel?.textAlignment = .center
        btnDestroy.layer.masksToBounds = true
        btnDestroy.titleLabel?.font = UIFont.systemFont(ofSize: 20)
        btnDestroy.setTitleColor(UIColor(red: 50/255, green: 71/255, blue: 1, alpha: 1), for: UIControl.State.normal)
        btnDestroy.addTarget(self, action: #selector(btnDestroyClick), for: UIControl.Event.touchUpInside)
        self.view.addSubview(btnDestroy)
        
        localView = UIView.init()
        localView.backgroundColor = UIColor.yellow
        localView.frame = CGRect(x: 10, y: 280, width: 150, height: 150)
        self.view.addSubview(localView)
        
        remoteView = UIView.init()
        remoteView.frame = CGRect(x: 10, y: 440, width: 150, height: 150)
        remoteView.backgroundColor = UIColor.blue
        self.view.addSubview(remoteView)
        
    }
    
    @objc func btnDestroyClick() {
        AgoraRtcEngineKit.destroy()
    }
    
    @objc func btnJoinChannelClick() {
        joinChannella()
    }
    
    @objc func btnLeaveChannelClick() {
        if (agoraKit != nil) {
            agoraKit.leaveChannel { (stats) -> Void in
                NSLog("打印了 离开频道")
            }
        }
    }
    
    func joinChannella() {
        let channelNameTemp = channelname
        
        
        let config = AgoraRtcEngineConfig()
        config.appId = appid
        config.areaCode = 0xFFFFFFFF
        let logConfig = AgoraLogConfig()
        logConfig.level = .info
        config.logConfig = logConfig
        
        agoraKit = AgoraRtcEngineKit.sharedEngine(with: config, delegate: self)
        agoraKit.setChannelProfile(.liveBroadcasting)
        agoraKit.setAudioProfile(.musicHighQualityStereo, scenario: .gameStreaming)
        let clientRoleOption = AgoraClientRoleOptions()
        clientRoleOption.audienceLatencyLevel = .ultraLowLatency
        agoraKit.setClientRole(.broadcaster)
        //agoraKit.setClientRole(.broadcaster, options: clientRoleOption)//主播
        //agoraKit.setClientRole(.audience, options: clientRoleOption)//观众
        agoraKit.enableAudio()
        agoraKit.enableVideo()
        let mediaOption = AgoraRtcChannelMediaOptions()
        //如果用相同的uid，则两个主播加入频道后无声音
        let result = agoraKit.joinChannel(byToken: token, channelId: channelNameTemp, info: nil, uid: 0, options: mediaOption)
        if result != 0 {
            NSLog("打印了 进入频道失败 \(result)")
        }
        else {
            NSLog("打印了 进入频道返回0")
        }
        
        
        
    }
    
    func setupLocalVideo() {
        // 启用视频模块
        //agoraKit?.enableVideo()
        let videoCanvas = AgoraRtcVideoCanvas()
        videoCanvas.uid = 0
        videoCanvas.renderMode = .hidden
        videoCanvas.view = localView
        // 设置本地视图
        agoraKit?.setupLocalVideo(videoCanvas)
    }
    
    func setupRemoteVideo(_ uid: UInt) {
        let videoCanvas = AgoraRtcVideoCanvas()
        videoCanvas.uid = uid
        videoCanvas.renderMode = .hidden
        videoCanvas.view = remoteView
        // 设置远端视图
        agoraKit?.setupRemoteVideo(videoCanvas)
    }
}

extension ZSNBroadcastVC: AgoraRtcEngineDelegate {
    
    func rtcEngine(_ engine: AgoraRtcEngineKit, didOccurWarning warningCode: AgoraWarningCode) {
        NSLog("打印了 rtcEngine(_ engine: AgoraRtcEngineKit, didOccurWarning warningCode: AgoraWarningCode)")
    }
    
    func rtcEngine(_ engine: AgoraRtcEngineKit, didOccurError errorCode: AgoraErrorCode) {
        NSLog("打印了 rtcEngine(_ engine: AgoraRtcEngineKit, didOccurError errorCode: AgoraErrorCode)")
    }
    
    func rtcEngine(_ engine: AgoraRtcEngineKit, didJoinChannel channel: String, withUid uid: UInt, elapsed: Int) {
        NSLog("打印了 rtcEngine(_ engine: AgoraRtcEngineKit, didJoinChannel channel: String, withUid uid: UInt, elapsed: Int)")
        
        setupLocalVideo()
    }
    
    func rtcEngine(_ engine: AgoraRtcEngineKit, didJoinedOfUid uid: UInt, elapsed: Int) {
        NSLog("打印了 rtcEngine(_ engine: AgoraRtcEngineKit, didJoinedOfUid uid: UInt, elapsed: Int)")
        //record remote uid
        //remoteUid = uid
        
        setupRemoteVideo(uid)
    }
    
    func rtcEngine(_ engine: AgoraRtcEngineKit, didOfflineOfUid uid: UInt, reason: AgoraUserOfflineReason) {
        NSLog("打印了 didOfflineOfUid 远端用户（通信场景）/主播（直播场景）离开当前频道回调 正常离开或掉线，把远端view根据进行处理")
    }
}
